<?php
namespace models\service;
//use PEAR;

class InboxService {

	protected $ci;
	public $lastBerkas;
	
	public function __construct() {
		$this -> ci = &get_instance();
		
	}

	public function startNewFlow($berkas, $profile, $jenisProcedure=0){
		$inbox = new \models\entities\Inbox;
		$inbox->setId($berkas);
		
		// HARDCODE, use to be table jenis_prosedur 
		if ($jenisProcedure==0){
			$criteria = array('profile' => $profile);
			$procedureStep = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findBy($criteria);
			$sps=0;
			
			foreach ($procedureStep as $ps){
				if ($ps->getId() == 1 || $ps->getId() == 5){
					$sps = $ps;
				}
			}
			
			$inbox->setProcedureStep($sps);
			$inbox->setCondition("START");
			$inbox->setCreatedDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
			$berkas->setStartDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
			
			$berkasActivity = new \models\entities\BerkasActivity;
			$berkasActivity->setBerkas($berkas);
			$berkasActivity->setProcedureStep($sps);			
			$berkasActivity->setAction("START");			
			$berkasActivity->setProfile($profile);
			$user = CurrentUser::user();
			$berkasActivity->setUser($user->getUserId());
		}
		try {
			$this->ci->em->persist($berkas);
		    $this->ci->em->flush();	
			
			$this->ci->em->persist($inbox);
		    $this->ci->em->flush();	
			
			$this->ci->em->persist($berkasActivity);
		    $this->ci->em->flush();	
			return TRUE;
		} catch (Exception $e){
			return FALSE;
		}
	}
	
	
	public function sendMailBerkasFinal($userId, $idBerkas, $status=""){
		$criteria = array('userId'=> $userId);
		$userGetNotif = $this->ci->em->getRepository('\models\entities\User')->findOneBy($criteria);
		$criteria = array('id'=> $idBerkas);
		$berkas = $this->ci->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
		$userEmail = $userGetNotif->getMail();
		$idBerkas = $berkas->getId();
		
		// sent notifikasi mail
		$this->ci->load->library('email');

		$this->ci->email->from('laporan@perpuseru.org', 'Administrator MIS Perpuseru');
		$this->ci->email->to($userEmail);

		if($status == "")
		{
			$this->ci->email->subject('Laporan '.$idBerkas.' Telah Di APPROVED!');
			$message=array();
			$message[] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
			$message[] = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
			$message[] = '<meta content="text/html; charset=utf-8" http-equiv="Content-type">';
			$message[] = '<head>';
			$message[] = '<title> Your New Password : Noor CMS | '.$idBerkas.' </title>';
			$message[] = '</head>';
			$message[] = '<body>';
			$message[] = 'Dear '.$userGetNotif->getName();
			$message[] = 'This Email was sent to you in order to inform you that your <strong>Password</strong> has been reset.<br/>';
			//$message[] = '<img src="https://o.twimg.com/2/proxy.jpg?t=HBhOaHR0cHM6Ly9jZG4ucGF0aC5jb20vcGhvdG9zMi85ZjBiYTAxMS03ODI1LTRkYzUtOTI4ZC00ZDc1MjdlMjQ4ZDMvb3JpZ2luYWwuanBnFMAHFIAKABYAEgA&s=XFMf7htybpV_4m_s2mH-fgpKCWl66a5DSCJw18rsGQs"></img><br/>';
			$message[] = 'Bellow is your <strong> New Password :</strong><br/>';
			$message[] = 'Your <strong>Username </strong>is : <strong> '.$userGetNotif->getUserId().'</strong><br/>';
			$message[] = 'Your <strong>New Password </strong>is : <strong> '.$userGetNotif->getName().'</strong><br/>';
			$message[] = 'Please change your <strong>New Password</strong> as soon as you login to the system in order to avoid any security issues.<br/>';
			$message[] = '</body></html>';
		}
		else
		{
			$this->ci->email->subject('Laporan '.$idBerkas.' Telah Di Dikembalikan!');
			$message=array();
			$message[] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
			$message[] = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
			$message[] = '<meta content="text/html; charset=utf-8" http-equiv="Content-type">';
			$message[] = '<head>';
			$message[] = '<title> Your New Password : Noor CMS | '.$idBerkas.' </title>';
			$message[] = '</head>';
			$message[] = '<body>';
			$message[] = 'Dear '.$userGetNotif->getName();
			$message[] = 'This Email was sent to you in order to inform you that your <strong>Password</strong> has been reset.<br/>';
			//$message[] = '<img src="https://o.twimg.com/2/proxy.jpg?t=HBhOaHR0cHM6Ly9jZG4ucGF0aC5jb20vcGhvdG9zMi85ZjBiYTAxMS03ODI1LTRkYzUtOTI4ZC00ZDc1MjdlMjQ4ZDMvb3JpZ2luYWwuanBnFMAHFIAKABYAEgA&s=XFMf7htybpV_4m_s2mH-fgpKCWl66a5DSCJw18rsGQs"></img><br/>';
			$message[] = 'Bellow is your <strong> New Password :</strong><br/>';
			$message[] = 'Your <strong>Username </strong>is : <strong> '.$userGetNotif->getUserId().'</strong><br/>';
			$message[] = 'Your <strong>New Password </strong>is : <strong> '.$userGetNotif->getName().'</strong><br/>';
			$message[] = 'Please change your <strong>New Password</strong> as soon as you login to the system in order to avoid any security issues.<br/>';
			$message[] = '</body></html>';
		}
		$message = implode(PHP_EOL, $message);
		$this->ci->email->message($message);

		$this->ci->email->send();

		//echo $this->ci->email->print_debugger();
		//die('asshole');
	
	}
	
	public function nextInboxStep($inbox, $profile, $condition){
		/* validation, only certain profile to access inbox transition */
		if ($inbox->getProcedureStep()->getProfile()->getId() != $profile->getId()){
			// not authorize the profile id is not match with inbox profile	
			return false;
		}
			
		$criteria = array('origin' => $inbox->getProcedureStep(), 'condition' => $condition);
		$procedureTransition = $this->ci->em->getRepository('\models\entities\ProcedureTransition')->findOneBy($criteria);
		$user = CurrentUser::user();
		
		if ($procedureTransition != NULL){
			if ($procedureTransition->getDest() == NULL){
				// FINISH
				$criteria = array('id'=> $inbox->getId());
				$berkas = $this->ci->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
				
				$berkas->setApprover($user->getUserId());
				$berkas->setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
				$berkas->setResult("FINISH");
				//Get Reporter
				$userReporter = $berkas->getReporter();
				//$serv = new models\service\AdministrationService;
				//$this -> sendMailBerkasFinal($userReporter,$inbox->getId());

				$berkasActivity = new \models\entities\BerkasActivity;
				$berkasActivity->setBerkas($berkas);
				$berkasActivity->setProcedureStep($inbox->getProcedureStep());
				$berkasActivity->setProfile($profile);
				$berkasActivity->setAction("FINISH");
				$user = CurrentUser::user();
				$berkasActivity->setUser($user->getUserId());
				
				try {
					$this->ci->em->persist($berkasActivity);
				    $this->ci->em->flush();
										
					$this->ci->em->remove($inbox);
				    $this->ci->em->flush();	
					return TRUE;
				} catch (Exception $e){
					return FALSE;
				}
			} else {
				
				if ($procedureTransition->getCondition() == "CANCEL"){
					
					//die('CANCEL');
					$criteria = array('id'=> $inbox->getId());
					$berkas = $this->ci->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
					$user = CurrentUser::user();
					$berkas->setApprover($user->getUserId());
					$berkas->setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
					$berkas->setResult("CANCEL");
					
					$berkasActivity = new \models\entities\BerkasActivity;
					$berkasActivity->setBerkas($berkas);
					$berkasActivity->setProcedureStep($inbox->getProcedureStep());
					$berkasActivity->setProfile($profile);
					$berkasActivity->setAction("CANCEL");
					$user = CurrentUser::user();
					$berkasActivity->setUser($user->getUserId());
					
					try {
						$this->ci->em->persist($berkasActivity);
					    $this->ci->em->flush();
											
						//$this->ci->em->persist($berkasActivity);
					    //$this->ci->em->flush();	
						
						$this->ci->em->remove($inbox);
					    $this->ci->em->flush();	
						return TRUE;
					} catch (Exception $e){
						return FALSE;
					}	
				} else {
					$criteria = array('id'=> $procedureTransition->getDest());
					$procedureStep = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
					$inbox->setProcedureStep($procedureStep);
					$inbox->setCondition($procedureTransition->getCondition());
					$inbox->setCreatedDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
					$criteria = array('id'=> $inbox->getId());
					$berkas = $this->ci->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
					$userReporter = $berkas->getReporter();
					//$serv = new models\service\AdministrationService;
					//$this -> sendMailBerkasFinal($userReporter,$inbox->getId(),'NOK');
					$isSpecialFlow = FALSE;
					if ($berkas->getTipe()->getId() == "TRAINING" && $condition == "NOK"){
						$criteria = array('id'=> $berkas);
						$berkasTraining = $this->ci->em->getRepository('\models\entities\BerkasTraining')->findOneBy($criteria);
						if ($berkasTraining->getJenisTraining()->getJenisFlow() == 2){
							$isSpecialFlow = TRUE;
							$inbox->setJumlahVerify(0);
							$inbox->setJumlahApprover(0);
							$inbox->setLastVer(NULL);
							$inbox->setLastApp(NULL);
						}
					}
					
					$berkasActivity = new \models\entities\BerkasActivity;
					$berkasActivity->setBerkas($berkas);
					$berkasActivity->setProcedureStep($procedureStep);
					$berkasActivity->setProfile($profile);
					$berkasActivity->setAction($procedureTransition->getCondition());
					$user = CurrentUser::user();
					$berkasActivity->setUser($user->getUserId());
					
					try {
						$this->ci->em->persist($inbox);
					    $this->ci->em->flush();	
						
						$this->ci->em->persist($berkasActivity);
					    $this->ci->em->flush();	
						return TRUE;
					} catch (Exception $e){
						return FALSE;
					}					
				}				
			}
		}
		
	}
	
}
